package com.hq.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hq.zb.exception.BizException;
import com.hq.zb.exception.BizExceptionEnum;
import com.hq.zb.mapper.RoleMenuMapper;
import com.hq.zb.mapper.UserMenuMapper;
import com.hq.zb.model.Menu;
import com.hq.zb.model.UserMenu;
import com.hq.zb.service.IMenuService;
import com.hq.zb.service.IUserMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户菜单关系表 服务实现类
 * </p>
 *
 * @author huanghanrui
 * @since 2022-03-07
 */
@Service
public class UserMenuServiceImpl extends ServiceImpl<UserMenuMapper, UserMenu> implements IUserMenuService {

    @Autowired
    private UserMenuMapper userMenuMapper;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public void assignUserMenu(UserMenu userMenu) {
        if (userMenu.getUserId() == null) {
            throw new BizException(BizExceptionEnum.DATA_NOT_NULL, "用户ID必填.");
        }
        userMenuMapper.deleteUserMenu(userMenu);
        List<Integer> menuIds = userMenu.getMenuIds();
        if (CollectionUtil.isNotEmpty(menuIds)) {
            List<Menu> menus = menuService.selectBatchIds(menuIds);
            if (CollectionUtil.isNotEmpty(menus)) {
                for (Menu menu : menus) {
                    UserMenu roleMenu = new UserMenu();
                    roleMenu.setUserId(userMenu.getUserId());
                    roleMenu.setMenuId(menu.getMenuId());
                    userMenuMapper.insert(roleMenu);
                }
            }
        }
    }

    @Override
    public List<Integer> queryMenuId(UserMenu userMenu) {
        //判断用户是否分配了对立菜单，没有的默认角色菜单
        Wrapper<UserMenu> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userMenu.getUserId());
        Integer count = userMenuMapper.selectCount(wrapper);
        if (count <= 0) {
            //查询角色
            return roleMenuMapper.queryMenuIdByRoleUser(userMenu.getUserId());
        }
        return userMenuMapper.queryMenuIds(userMenu.getUserId());
    }
}
